﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;


namespace Confessor
{
    public partial class FormConfessor : Form
    {
        XFileActions xFA;
        Interogation interogation;
        ScanObject scanObject;
        XRegEx xRegEx;

        // Default form initialize constructor.
        public FormConfessor()
        {
            InitializeComponent();
            xFA = new XFileActions();
            xRegEx = new XRegEx();
            interogation = new Interogation();
            scanObject = new ScanObject();
        }

        // Upload file containing IP's and parse through it.
        private void buttonFileUpload_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Application.StartupPath;
            openFileDialog.Filter = "csv Files(*.csv)|*.csv|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            try
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    textBoxFileOpen.Text = openFileDialog.FileName;
                    xFA.HostsFromFileToArray(scanObject, textBoxFileOpen.Text);
                    updateNumOfHosts();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

        }

        // Upload DataGrid IP's manually entered.
        private void buttonDGIPs_Click(object sender, EventArgs e)
        {
            // Verify there is something to scan.
            for (int i = 0; i < dataGridIPs.Rows.Count; i++)
            {
                if (dataGridIPs.Rows[i].Cells[0].Value != null)
                {
                    bool lookLikeIP = xRegEx.RegExTest(4, dataGridIPs.Rows[i].Cells[0].Value.ToString());
                    bool isIP = xRegEx.RegExTest(0, dataGridIPs.Rows[i].Cells[0].Value.ToString());
                    bool isWindowsHost = xRegEx.RegExTest(3, dataGridIPs.Rows[i].Cells[0].Value.ToString());

                    if (lookLikeIP)
                    {
                        if (isIP)
                        {
                            ConfessorHostsObject conStat = new ConfessorHostsObject();
                            conStat.IP = dataGridIPs.Rows[i].Cells[0].Value.ToString();
                            scanObject.Hosts.Add(conStat);
                        }
                        else
                        {
                            MessageBox.Show(dataGridIPs.Rows[i].Cells[0].Value.ToString() + " is not a valid IP");
                        }
                    }

                    if (isWindowsHost && lookLikeIP == false)
                    {
                        ConfessorHostsObject conStat = new ConfessorHostsObject();
                        conStat.IP = dataGridIPs.Rows[i].Cells[0].Value.ToString();
                        scanObject.Hosts.Add(conStat);
                    }

                    else if (isWindowsHost == false)
                    {
                        MessageBox.Show(dataGridIPs.Rows[i].Cells[0].Value.ToString() + " is not a valid hostname");
                    }
                }
            }
            updateNumOfHosts();
        }

        // Kicks off the main program, shoves majority of the work to a background worker (seperate thread) to avoid locking the UI.
        // Next version, look into reimplementing multi threading (It has some bugs that need to be worked out (Locking).)
        private void buttonScan_Click(object sender, EventArgs e)
        {
            scanObject.InvestigationID = textBoxInvestigationID.Text;
            scanObject.InvestigationName = textBoxInvestigationName.Text;
            scanObject.ConfessorSharePath = textBoxToolsShare.Text;
            scanObject.ResultsSharePath = textBoxResultsShare.Text;
            scanObject.UserName = textBoxUserName.Text;
            scanObject.Password = textBoxPassword.Text;
            scanObject.ResultsDirectory = Application.StartupPath + @"\Results\" + scanObject.InvestigationID;
            
            // Check to see if all fields are appropriately filled in.
            if (scanObject.InvestigationID == string.Empty || scanObject.ConfessorSharePath == string.Empty || scanObject.ConfessorSharePath == string.Empty || scanObject.ResultsSharePath == string.Empty || scanObject.UserName == string.Empty || scanObject.Password == string.Empty)
            {
                MessageBox.Show("You must fill out the following fields: Investigation ID, Tool Share Path, Results Share Path, Username, and Password");
                return;
            }
            
            // Check to see if there is something to scan, alert if not.
            if(scanObject.Hosts.Count == 0)
            {
                MessageBox.Show("There is nothing to scan, upload some IP's");
                return;
            }

            // Set Progress Bar Values.
            progressBar.Value = 0;
            progressBar.Maximum = scanObject.Hosts.Count;

            // set up scan directory
            xFA.MakeDirectory(scanObject.ResultsDirectory);

            // Create the Confessor script for this Confessor run.
            BuildConfessorScript.CreateConfessorScript(treeView1, scanObject);

            // Send intensive processing to the background worker thread.
            bgWorker.RunWorkerAsync(scanObject);
        }

        // Implement in next version
        private void buttonSaveScanConfig_Click(object sender, EventArgs e)
        {

        }

        // Implement in next version
        private void buttonLoadScanConfig_Click(object sender, EventArgs e)
        {

        }

        // About the program.  Opens new form displaying information.
        private void labelAbout_Click(object sender, EventArgs e)
        {
            AboutConfessor formAbout = new AboutConfessor();
            formAbout.Show();
        }

        // Update Number of Host label
        private void updateNumOfHosts()
        {
            textBoxHostIPArray.Clear();
            foreach (ConfessorHostsObject conf in scanObject.Hosts)
            {
                string p = conf.IP + "\r\n";
                textBoxHostIPArray.Text += p;
            }
            labelNumOfHosts.Text = scanObject.Hosts.Count.ToString();
        }

        // Update the progress bar.
        private void progressBarUpdate(int cur)
        {
            progressBar.Value = cur;
            progressBar.Update();
        }

        // Reset the form
        private void buttonReset_Click(object sender, EventArgs e)
        {
            scanObject.Hosts.Clear();
            dataGridIPs.Rows.Clear();
            scanObject.InvestigationID = string.Empty;
            textBoxInvestigationID.Text = string.Empty;
            scanObject.InvestigationName = string.Empty;
            textBoxInvestigationName.Text = string.Empty;
            scanObject.InvestigationID = string.Empty;
            textBoxInvestigationID.Text = string.Empty;
            scanObject.ConfessorSharePath = string.Empty;
            textBoxToolsShare.Text = string.Empty;
            scanObject.ResultsSharePath = string.Empty;
            textBoxResultsShare.Text = string.Empty;
            textBoxHostIPArray.Text = string.Empty;
            textBoxFileOpen.Text = string.Empty;
            labelNumOfHosts.Text = string.Empty;
        }

        // Close the Confessor program
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region BG Worker
        // Majority of the work to gather data is performed here and where it calls BuildConfessorScript and Interogation classes.
        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ScanObject scanObject = (ScanObject)e.Argument;

            // Loop through scanObject.Hosts and connect via WMI to kick of the interogation of the host.
            int y = 0;
            int x = scanObject.Hosts.Count;

            while (y < x)
            {
                interogation.InitiateWMI(scanObject, y);
                y++;
                bgWorker.ReportProgress(y);
            }

            e.Result = scanObject;
        }
        
        // Update the Progress bar from bgWorker Thread.
        private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.PerformStep();
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            scanObject = (ScanObject)e.Result;
        }
        #endregion

        private void dataGridIPs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
